# -*- coding: utf-8 -*-

from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, RequestContext
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.conf import settings
from django.contrib import messages

@user_passes_test(lambda u: u.is_anonymous(), login_url='/')
def login(request):
    next = request.GET.get('next', False)

    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            auth_login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            if not next:
                next = '/lista/'

            return HttpResponseRedirect(next)
        else:
            messages.warning(request, u'Usuário ou senha inválido')
    else:
        form = AuthenticationForm()

    context = {
        'form': form
    }

    return render_to_response(
                'login.html',
                context,
                RequestContext(request),
                )

def index(request):
    return render_to_response(
        'index.html',
        {},
        RequestContext(request),
        )


